package com.tuanzi.service.impl;

import com.tuanzi.dao.*;
import com.tuanzi.entity.FlowerPot;
import com.tuanzi.service.PotService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author tuanzi
 * @version 1.0
 * @date 2022/4/4 17:25
 */

@Service
public class PotServiceImpl implements PotService {

    // 注入类
    @Resource
    private FlowerPotMapper flowerPotMapper;

    // 注入temper_day实现类
    @Resource
    private TemperatureDayMapper temperatureDayMapper;

    // 注入temper_week实现类
    @Resource
    private TemperatureWeekMapper temperatureWeekMapper;

    // 注入humidity_day的实现类
    @Resource
    private HumidityDayMapper humidityDayMapper;

    // 注入humidity_week实现类
    @Resource
    private HumidityWeekMapper humidityWeekMapper;

    // 添加一个新的花盆
    @Transactional
    @Override
    public FlowerPot addFlowerPot(Integer uid, String name, String description) {
        Integer integer = flowerPotMapper.insertPot(name, description, uid);
        if (integer != -1){
            // 添加成功，查找并返回这个花盆
            FlowerPot flowerPot = flowerPotMapper.selectByName(name);
            return flowerPot;
        }else{
            return null;
        }
    }

    // 删除一个花盆和花盆相关的所有类
    // 添加事务
    @Transactional
    @Override
    public FlowerPot deleteFlowerPot(Integer fid) {

        // 首先根据pid删除所有的温度信息
        Integer result_temperature_day = temperatureDayMapper.deleteByFid(fid);
        Integer result_temperature_week = temperatureWeekMapper.deleteByFid(fid);

        // 之后删除所有湿度的信息
        Integer result_humidity_day = humidityDayMapper.deleteByFid(fid);
        Integer result_humidity_week = humidityWeekMapper.deleteByFid(fid);

        // 对查询到的温度进行判断
        if(result_humidity_day != -1 && result_humidity_week != -1
                && result_temperature_day != -1 && result_temperature_week != -1){
            // 这里说明删除成功, 这里其实可以通过查找判断有没有删除完成，这里节省时间直接对操作进行判断
            // 会出现bug

            FlowerPot pot = flowerPotMapper.selectById(fid);

            // 删除花盆
            int result =flowerPotMapper.deleteById(fid);
            if(result != 1){
                // 删除花盆失败 这里为了节省时间也不使用查询确定了，直接进行使用
                return null;
            }
            return pot;
        }

        return null;
    }

}
